from datetime import datetime
from app.db import db

#  用户表: b_user
class BUser(db.Model):
    __tablename__ = 'b_user'

    username = db.Column(db.String(50), unique=True, nullable=False, comment='登录用户名')
    password = db.Column(db.String(255), nullable=False, comment='密码(建议加密存储)')
    role = db.Column(db.String(2), nullable=False, default='1', comment='角色(如0-普通用户､1-高级,2-管理员)')
    status = db.Column(db.String(1), nullable=False, default='1', comment='状态(如0-禁用､1-正常)')
    nickname = db.Column(db.String(20), comment='用户昵称')
    avatar = db.Column(db.String(100), comment='头像链接')
    mobile = db.Column(db.String(13), comment='手机号')
    email = db.Column(db.String(50), comment='邮箱')
    gender = db.Column(db.String(1), comment='性别(如0-女､1-男､2-其他)')
    lastLogin = db.Column(db.DateTime(6), comment='最后登录时间')
    description = db.Column(db.Text, comment='个人简介(大文本)')
    create_time = db.Column(db.DateTime(6), nullable=False, default=datetime.utcnow, comment='用户创建时间')
    score = db.Column(db.Integer, default=0, comment='积分')
    push_email = db.Column(db.String(40), comment='邮件推送开关(如0-关､1-开)')
    push_switch = db.Column(db.Boolean, comment='全局推送开关(布尔值)')
    admin_token = db.Column(db.String(32), comment='管理员令牌(若区分权限)')
    token = db.Column(db.String(32), comment='前端登录态令牌(如JWT)')
    id = db.Column(db.BigInteger, primary_key=True, autoincrement=True, comment='用户唯一主键ID')

    # 一对多关系：用户有多张订单
    orders = db.relationship('BOrder', backref='user', lazy=True)


    def to_dict(self):
        return {
            'id': self.id,
            'username': self.username,
            'password': self.password,  # 注意：实际项目中不应直接返回密码
            'role': self.role,
            'status': self.status,
            'nickname': self.nickname,
            'mobile': self.mobile,
            'email': self.email,
            'create_time': self.create_time.isoformat() if self.create_time else None
        }
